# coding:utf-8
__author__ = 'admin zhoushuang'
__date__ = '2016/10/8'
__all__ = ['BaseHandler']

import logging
from common_functions import *


class BaseHandler(object):
    """ The base handler class

    All module handler class is extended from BaseHanlder,
    and the subclass need overried handle(reqdict) function.

    """

    def __init__(self):
        self.echo = None

    def handle(self, reqdict):
        """处理请求dict , 一般的moduler hanlder 重载此方法即可
        :param reqdict:  请求dict
        :return:
        """
        pass

    def handle_agent_side(self, reqdict, request_socket):
        """处理客户端请求，从socket中按行读取key=value形式的参数，组成请求dict, 然后在执行handle方法
        一些特殊的module hanlder需要重载此方法

        :param reqdict:  请求参数 dict， 由agentd传递过来
        :param request_socket: 链接socket
        :return:
        """
        socket_in = request_socket.makefile('rt')
        socket_out = request_socket.makefile('wt')
        while True:
            line = socket_in.readline()
            if line.startswith(gvars.EOFSTR):
                break
            if not line.isspace():
                kv = line.strip().split('=', 1)
                if len(kv) == 2:
                    reqdict[kv[0].strip()] = kv[1].strip()

        logging.info("receive request : {}".format(reqdict))

        self.echo = socket_out
        self.handle(reqdict)
        socket_out.write('\n' + gvars.EOFSTR + '\n')
        socket_out.flush()
        socket_in.close()
        socket_out.close()
        pass

    def handle_request_side(self, reqdict, address_tuple):
        """发送请求字典到远端，并读取返回结果，并检查结果是否有ERROR 或 FAILED

        一些特殊处理的mod hanlder 需要重载此方法

        :param reqdict:     请求字典
        :param address_tuple:  （ip, port） 远端ip和端口
        :return:
        :raise:  ValueError 检查返回字符串是否有ERROR 或 FAILED， 如果有就抛出异常
        """
        response = sendrequest(address_tuple, reqdict)
        print response
        check_response_string(response)